package org.algorithm.wE1.链表;

import org.algorithm.common.ListNode;
import org.junit.Test;

/**
 * @author
 * @Date 2022/2/22
 * @Link {https://leetcode-cn.com/problems/SLwz0R/}
 */
public class 删除链表的倒数第n个结点 {


    @Test
    public void test() {
        ListNode listNode = removeNthFromEnd(ListNode.build(1, 2), 2);
        System.out.println("listNode = " + listNode);
        ListNode.print(listNode);
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyNode  = new ListNode(-1);
        dummyNode.next = head;
        ListNode slowNode = dummyNode;
        ListNode fastNode = dummyNode;
        //fastNode先走n步当n==0时 slowNode开始一起走
        while (fastNode.next!=null){
            fastNode = fastNode.next;
            if(n==0){
                slowNode = slowNode.next;
            }else {
                n--;
            }
        }
        //删除slowNode.next
        slowNode.next = slowNode.next.next;;
        return  dummyNode.next;
    }
}
